<template>
  <div class="writeScene">
    <header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/projectRoleMain' }">角色</el-breadcrumb-item>
        <el-breadcrumb-item>{{isWrite ? '编辑' : '添加'}}</el-breadcrumb-item>
      </el-breadcrumb>
    </header>
    <div class="title">{{isWrite ? '编辑角色' : '添加角色'}}</div>
    <!-- 中间表单 -->
    <div class="main">
      <div class="header">
        <span></span>
        <p>角色信息</p>
      </div>
      <el-form :model="param" :rules="rules" ref="ruleForm" label-width="290px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="param.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="remark">
          <el-input
            type="textarea"
            placeholder="请输入角色描述"
            v-model="param.remark"
            maxlength="50"
            show-word-limit
            :rows="8"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限设置：" prop="webMenuList">
          <div class="wrap">
            <div class="title" @click="contentShow">
              <span>{{name}}</span>
              <div class="allCheck">
                全选
                <el-checkbox v-model="allCheckd" @change="handleSelectAll"></el-checkbox>
              </div>
            </div>
            <div class="content" :style="{display:(isWrite)?'block':'none'}">
              <template v-if="webMenuList!=null && webMenuList.length>0">
                <div class="item" v-for="(first,firIndex) in webMenuList" :key="first.webMenuId">
                  <div class="itemHeader" @click="itemContentShow(firIndex)">
                    <span>{{first.name}}</span>
                    <span
                      style="color:#4868FF;margin-left:5px;"
                    >{{first.children && first.children.length>0 ? '+' : '-'}}</span>
                    <el-checkbox
                      v-model="groupList"
                      :label="first.webMenuId"
                      :key="first.webMenuId"
                      @change="firstChanged(firIndex)"
                    >{{''}}</el-checkbox>
                  </div>
                  <div class="itemContent" :style="{display:(isWrite)?'block':'none'}">
                    <div v-for="(second,secondIndex) in first.children" :key="second.webMenuId">
                      <div class="thirdHeader">
                        <span>{{second.name}}</span>
                        <el-checkbox
                          v-model="groupList"
                          :label="second.webMenuId"
                          :key="second.webMenuId"
                          @change="secondChanged(firIndex,secondIndex)"
                          :title="second.name"
                        >{{''}}</el-checkbox>
                      </div>
                      <div class="thirdContent">
                        <div v-for="third in second.children" :key="third.webMenuId">
                          <div>
                            <span>{{third.name}}</span>
                            <el-checkbox
                              v-model="groupList"
                              :label="third.webMenuId"
                              :key="third.webMenuId"
                              @change="thirdChanged(firIndex,secondIndex)"
                              :title="third.name"
                            >{{''}}</el-checkbox>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
          <div v-if="isShowTip" class="errorText">请选择角色权限</div>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="submitForm('ruleForm')" >确定</el-button>
    </div>
  </div>
</template>

<script>
import {
  addRole,
  updateRole,
  getRole,
  getPermissionList
} from '../../../../api/projectRole'
export default {
  data () {
    return {
      isShowTip: false,
      param: {
        roleId: '',
        roleName: '',
        remark: '',
        webMenuList: [],
        webMenuIds: []
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      name: '',
      webMenuList: [],
      groupList: [],
      allCheckd: false,
      supWebMenu: ''
    }
  },
  mounted () {
    this.getRoleInfo()
  },
  watch: {
    'param.webMenuList' (groups, oldGroups) {
      if (groups === null || oldGroups === null) return
      if (groups.toString() === oldGroups.toString()) return
      this.groupList = Array.from(groups, (obj) => obj.webMenuId)
    },
    groupList (groupList) {
      const authorityCodes = [] // 选中的权限
      if (this.webMenuList.length === 0) return
      groupList.forEach((o) => {
        const finder = this.webMenuList.find((child) => child.webMenuId === o)
        if (finder) {
          authorityCodes.push({
            webMenuId: finder.webMenuId,
            name: finder.name,
            parentId: finder.parentId,
            component: finder.component,
            path: finder.path,
            perms: finder.perms,
            isValid: finder.isValid,
            createTime: finder.createTime,
            updateTime: finder.updateTime,
            remark: finder.remark
          })
        }
        this.webMenuList.forEach((e) => {
          if (e.children === null) return
          const finder = e.children.find((child) => child.webMenuId === o)
          if (finder) {
            authorityCodes.push({
              webMenuId: finder.webMenuId,
              name: finder.name,
              parentId: finder.parentId,
              component: finder.component,
              path: finder.path,
              perms: finder.perms,
              isValid: finder.isValid,
              createTime: finder.createTime,
              updateTime: finder.updateTime,
              remark: finder.remark
            })
          }
          const thirdChild = e.children
          thirdChild.forEach((e) => {
            if (e.children === null) return
            const finder = e.children.find((child) => child.webMenuId === o)
            if (finder) {
              authorityCodes.push({
                webMenuId: finder.webMenuId,
                name: finder.name,
                parentId: finder.parentId,
                component: finder.component,
                path: finder.path,
                perms: finder.perms,
                isValid: finder.isValid,
                createTime: finder.createTime,
                updateTime: finder.updateTime,
                remark: finder.remark
              })
            }
          })
        })
      })
      this.param.webMenuList = authorityCodes
      this.param.webMenuIds = Array.from(
        this.param.webMenuList,
        (obj) => obj.webMenuId
      )
    }
  },
  methods: {
    getRoleInfo () {
      getPermissionList().then((res) => {
        if (res.data.code === 200) {
          const result = res.data.data
          this.webMenuList = result.children
          this.name = result.name
          this.supWebMenu = {
            webMenuId: result.webMenuId,
            name: result.name,
            parentId: result.parentId,
            component: result.component,
            path: result.path,
            perms: result.perms,
            remark: result.remark
          }
        }
      })
      const roleId = sessionStorage.getItem('roleId')
      if (roleId) {
        getRole(roleId).then((res) => {
          if (res.data.code === 200) {
            this.param = res.data.data
            const groups = this.param.webMenuList
            this.groupList = Array.from(groups, (obj) => obj.webMenuId)
            this.isAllCheckd()
          }
        })
      }
      window.onbeforeunload = function (e) {}
    },
    submitForm (ruleForm) {
      this.isShowTip = !this.groupList.length
      this.$refs[ruleForm].validate((valid) => {
        if (valid && !this.isShowTip) {
          if (this.allCheckd) {
            this.param.webMenuList.push(this.supWebMenu)
            this.param.webMenuIds.push(this.supWebMenu.webMenuId)
          }
          if (this.isWrite) {
            this.param.webMenuIds.push(this.supWebMenu.webMenuId)
            this.param.webMenuIds = Array.from(new Set([...this.param.webMenuIds]))
            updateRole(this.param).then((res) => {
              if (res.data.code === 999 || res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.message
                })
                this.$store.dispatch('projectRole/updateTable', this.pageIndex)
                this.isShowTip = false
                this.$router.push('/projectRoleMain')
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.message
                })
              }
            })
          } else {
            addRole(this.param).then((res) => {
              if (res.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.message
                })
                this.$store.dispatch('projectRole/updateTable', this.pageIndex)
                this.isShowTip = false
                this.$router.push('/projectRoleMain')
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.message
                })
              }
            })
          }
        } else {
          this.$message({
            message: '请填写相关信息',
            type: 'error',
            duration: 500
          })
        }
      })
    },
    contentShow () {
      const element = document.getElementsByClassName('content')[0]
      if (element.style.display === 'none') {
        element.style.display = 'block'
      } else {
        element.style.display = 'none'
      }
    },
    itemContentShow (index) {
      const element = document.getElementsByClassName('itemContent')[index]
      if (element.style.display === 'none') {
        element.style.display = 'block'
      } else {
        element.style.display = 'none'
      }
    },
    isAllCheckd () {
      this.allCheckd = this.webMenuList.every((s) => {
        if (this.groupList.includes(s.webMenuId)) {
          return true
        }
      })
    },
    handleSelectAll () {
      const groupOptions = []
      if (this.allCheckd) {
        this.webMenuList.forEach((e) => {
          groupOptions.push(e.webMenuId)
          if (e.children) {
            e.children.forEach((o) => {
              groupOptions.push(o.webMenuId)
              if (o.children) {
                o.children.forEach((s) => {
                  groupOptions.push(s.webMenuId)
                })
              }
            })
          }
        })
        this.groupList = groupOptions
      } else {
        this.groupList = []
      }
    },

    firstChanged (firIndex) {
      this.isAllCheckd()
      const arr = this.webMenuList[firIndex]
      const isCheck = this.groupList.includes(arr.webMenuId)
      if (arr.children) {
        if (isCheck) {
          arr.children.forEach((e) => {
            if (!this.groupList.includes(e.webMenuId)) {
              this.groupList.push(e.webMenuId)
              if (e.children) {
                e.children.forEach((t) => {
                  this.groupList.push(t.webMenuId)
                })
              }
            }
          })
        } else {
          arr.children.forEach((e) => {
            this.groupList = this.groupList.filter((t) => t !== e.webMenuId)
            if (e.children) {
              e.children.forEach((s) => {
                this.groupList = this.groupList.filter(
                  (t) => t !== s.webMenuId
                )
              })
            }
          })
        }
      }
      // 一级未选中 则对应的二级都不选中
      // let tickCount = 0
      // const len = this.webMenuList.length
      // for (let i = 0; i < len; i++) {
      //   if (this.webMenuList[i].mychecked === true) {
      //     tickCount++
      //   }
      // }
      // if (tickCount === len) {
      //   // 二级全勾选  一级勾选
      //   this.allCheckd = true
      // } else {
      //   // 二级未全选  一级不勾选
      //   this.allCheckd = false
      // }
      // if (this.webMenuList[index].mychecked === false) {
      //   const childrenArray = this.webMenuList[index].children
      //   if (childrenArray) {
      //     for (let i = 0, len = childrenArray.length; i < len; i++) {
      //       childrenArray[i].mychecked = false
      //     }
      //   } // 一级选中  则对应的二级都选中
      // } else if (this.webMenuList[index].mychecked === true) {
      //   const childrenArray = this.webMenuList[index].children
      //   if (childrenArray) {
      //     for (let i = 0, len = childrenArray.length; i < len; i++) {
      //       childrenArray[i].mychecked = true
      //     }
      //   }
      // }
    },
    secondChanged (firIndex, secondIndex) {
      const arr = this.webMenuList[firIndex].children[secondIndex] // 当前操作权限
      if (arr.children) {
        arr.children.forEach((child) => {
          if (this.groupList.includes(arr.webMenuId)) {
            // 当前权限选中，那么子权限也应自动全部勾选
            this.groupList.push(child.webMenuId)
          } else {
            // 当前权限取消，那么子权限也应自动全部取消
            this.groupList = this.groupList.filter(
              (t) => t !== child.webMenuId
            )
          }
        })
      }

      const arrParent = this.webMenuList[firIndex] // 当前选中权限的父权限(一级)
      const firIndexArray = arrParent.children.map((item) => {
        return item.webMenuId
      }) // 属于该父权限的全部子权限
      const isFirstCheck = firIndexArray.some((webMenuId) => {
        return this.groupList.includes(webMenuId)
      }) // 判断属于该父权限的子权限是否全部勾选
      if (isFirstCheck) {
        this.groupList.push(arrParent.webMenuId) // 如果全部勾选，那么该父权限也应自动勾选
        // 再判断是否全选
        this.isAllCheckd()
      } else {
        // 如果不全部勾选
        if (this.groupList.includes(arrParent.webMenuId)) {
          // 如果原本父权限已经选中应自动取消勾选
          this.groupList = this.groupList.filter((t) => t !== arrParent.webMenuId)
          this.allCheckd = false
        }
      }

      // const childrenArray = this.webMenuList[firIndex].children
      // let tickCount = 0
      // // let unTickCount = 0
      // const len = childrenArray.length
      // for (let i = 0; i < len; i++) {
      //   if (childrenArray[i].mychecked === true) {
      //     tickCount++
      //   }
      //   // if (childrenArray[i].mychecked === false) {
      //   //   unTickCount++
      //   // }
      // }
      // if (tickCount === len) {
      //   // 二级全勾选  一级勾选
      //   this.webMenuList[firIndex].mychecked = true
      // } else {
      //   // 二级未全选  一级不勾选
      //   this.webMenuList[firIndex].mychecked = false
      //   this.allCheckd = false
      // }
    },
    thirdChanged (firIndex, secondIndex) {
      const arr = this.webMenuList[firIndex].children[secondIndex]
      const arrParent = this.webMenuList[firIndex]
      const secIndexArray = arr.children.map((item) => {
        return item.webMenuId
      })
      const isSecondCheck = secIndexArray.some((webMenuId) => {
        return this.groupList.includes(webMenuId)
      })
      if (isSecondCheck) {
        this.groupList.push(arr.webMenuId)

        // isFirstCheck判断一级权限是否勾选
        const firIndexArray = arrParent.children.map((item) => {
          return item.webMenuId
        })
        const isFirstCheck = firIndexArray.some((webMenuId) => {
          return this.groupList.includes(webMenuId)
        })
        if (isFirstCheck) {
          this.groupList.push(arrParent.webMenuId) // 一级权限勾选

          // 判断是否全选
          this.isAllCheckd()
        }
      } else {
        if (this.groupList.includes(arr.webMenuId)) {
          this.groupList = this.groupList.filter((t) => t !== arr.webMenuId)
          this.groupList = this.groupList.filter(
            (t) => t !== arrParent.webMenuId
          )
          this.allCheckd = false
        }
      }
    }

  },
  computed: {
    isWrite () {
      const userId = sessionStorage.getItem('roleId')
      return !!userId
    }
    // 全选CheckBox是否选中
    // allCheckd: {
    //   get () {
    //     const result = this.webMenuList.some((s) => {
    //       if (this.groupList.includes(s.webMenuId)) {
    //         return true
    //       }
    //     })
    //     return result
    //   },
    //   set (val) {

    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
@import "../../../../styles/writeBox.scss";
.writeScene {
  padding: 0 30px 30px 30px !important;
  .navButton {
    padding: 0;
    color: #4868ff;
  }
  .main {
    ::v-deep .el-form {
      position: relative;
      .el-form-item__error,.errorText{
        margin-left: 10px;
      }
      .el-form-item__label{
        width: 300px !important;
        padding: 0;
      }
      .el-form-item__content {
        display: inline-block;
      }
      .el-textarea{
        margin-left: 10px;
      }
      .el-input {
        margin-left: 10px;
        width: 400px;
      }
      .el-textarea__inner {
        width: 560px;
      }
      .el-input__count{
        right: 25px;
      }
      .wrap {
        width: 560px;
        margin-left: 10px;
        .title {
          width: 560px;
          height: 60px;
          font-size: 14px;
          line-height: 60px;
          background: rgba(87, 131, 255, 0.05);
          padding: 0 16px;
          border-bottom: 1px solid #e6e6e6;
          span {
            font-weight: 600;
            color: #333333;
          }
          .allCheck {
            float: right;
            .el-checkbox {
              margin-left: 10px;
            }
          }
        }
        .content {
          .el-checkbox {
            float: right;
          }
          .itemHeader {
            padding: 0px 6px 0px 16px;
            border-bottom: 1px solid #e6e6e6;
            color: #000000;
          }
          .itemContent {
            padding: 0px 6px 0px 16px;
            border-bottom: 1px solid #e6e6e6;
            color: #666666;

            .thirdContent {
              padding-left: 14px;
              font-weight: 100;
            }
          }
        }
      }
      .errorText {
        color: #f56c6c;
        font-size: 12px;
        line-height: 1;
        padding-top: 4px;
        position: absolute;
        top: 100%;
      }
    }
    .el-button {
    margin-left: 300px;
    margin-bottom: 30px;
    margin-top: 30px;
    width: 172px;
    height: 48px;
    background: rgba(72, 104, 255, 1);
    border-radius: 24px;
  }
  }
}
</style>
<style lang="scss">
.el-form-item.is-required:not(.is-no-asterisk)
  .el-form-item__label-wrap
  > .el-form-item__label:before,
.el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: "*";
  color: #4868ff;
  margin-right: 4px;
}
.el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
}
</style>
